export default `<template>
  <div class="map-box">
    <div class="map" id="map"></div>

    <!-- popup HTML -->
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content"></div>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import TileArcGISRest from "ol/source/TileArcGISRest";
import TileLayer from "ol/layer/Tile";
import View from "ol/View";
import { Cluster, OSM, Vector as VectorSource } from "ol/source";
import {
  Circle as CircleStyle,
  Fill,
  Stroke,
  Style,
  Text,
  Icon
} from "ol/style";
import { Vector as VectorLayer } from "ol/layer";
import Point from "ol/geom/Point";
import Feature from "ol/Feature";
import Overlay from "ol/Overlay";
import { toLonLat } from "ol/proj";
import { toStringHDMS } from "ol/coordinate";

import CONSTANT from "@/config/constant.js";
import mapData from "./data.js";
import pointImg from "@/images/device.png";

export default {
  name: "clickPointOverlay",
  data() {
    return {
      map: null,
      overlay: null,
      clusterSource: null
    };
  },

  methods: {
    //初始化地图
    init() {
      this.map = new Map({
        target: "map",
        layers: [
          new TileLayer({
            source: new TileArcGISRest({
              url: CONSTANT.GIS_URL
            })
          })
        ],
        view: new View({
          center: [113.0567, 23.67537],
          maxZoom: 18,
          minZoom: 8,
          zoom: 13,
          projection: "EPSG:4326"
        })
      });

      this.showPoints();
      this.addPopup();

      this.map.on("click", evt => {
        this.mapPointerClick(evt);
      });
    },

    //设置聚合图层的样式
    setClusterStyle(feature) {
      var features = feature.get("features");
      var size = features.length;
      var style;
      if (size == 1) {
        style = [
          new Style({
            image: new Icon({
              src: pointImg
            })
          })
        ];
      } else {
        style = new Style({
          image: new CircleStyle({
            radius: 18,
            stroke: new Stroke({
              color: "#fff"
            }),
            fill: new Fill({
              color: "#3399CC"
            })
          }),
          text: new Text({
            font: "15px sans-serif",
            text: size.toString(),
            fill: new Fill({
              color: "#fff"
            })
          })
        });
      }
      return style;
    },

    // 展示聚合点位
    showPoints() {
      // 聚合图层数据源
      this.clusterSource = new Cluster({
        distance: 100,
        source: new VectorSource({
          features: []
        })
      });

      const vectorLayer = new VectorLayer({
        source: this.clusterSource,
        style: feature => {
          return this.setClusterStyle(feature);
        }
      });

      let features = [];
      mapData.forEach(item => {
        if (item.gps_x != "" && item.gps_y != "") {
          let newObj = Object.assign({}, item);
          newObj.geometry = new Point([Number(item.gps_x), Number(item.gps_y)]);
          features.push(new Feature(newObj));
        }
      });
      this.clusterSource.getSource().addFeatures(features);
      this.map.addLayer(vectorLayer);

      /* 
        mapData是数组，每一项结构：
        {
            "domain_id": 10000029,
            "domain_name": "深圳市第一看守所",
            "domain_type_name": "看守所",
            "gps_x": "113.0131",
            "gps_y": "23.71433",
            "count": 0,
            "channel_id": "",
            "group_idx": 1
        } */
    },

    //添加弹出层
    addPopup() {
      this.overlay = new Overlay({
        element: document.getElementById("popup"),
        offset: [0, -13],
      });
      //添加 overlay 到 map
      this.map.addOverlay(this.overlay);

       // 关闭弹出层
      var closer = document.getElementById("popup-closer");
      closer.onclick = ()=> {
        this.overlay.setPosition(undefined);
        closer.blur();
        return false;
      };
    },

    //鼠标点击事件。若悬浮到设备上，则现在设备的具体信息
    mapPointerClick(evt) {
      let pixel = this.map.getEventPixel(evt.originalEvent);
      let featureMouseOver = this.map.forEachFeatureAtPixel(pixel, function(
        feature,
        layer
      ) {
        return feature;
      });
      let coordinate;
      if (featureMouseOver) {
        if (featureMouseOver.getProperties().features) {
          //聚合情况下
          if (featureMouseOver.getProperties().features.length == 1) {
            //只有一个要素
            let f = featureMouseOver.getProperties().features[0]; //获取该要素
            this.clusterSource.getSource().forEachFeature(feature => {
              if (f == feature) {
                coordinate =[Number(feature.get('gps_x')), Number(feature.get('gps_y'))];
                const hdms = toStringHDMS(toLonLat(coordinate));
                document.getElementById( "popup-content").innerHTML = 
                '<p style="font-weight:bold">通道类型：'+feature.get("domain_type_name")+'</p>'+
                '<p style="font-weight:bold">所属区域：'+feature.get("domain_name")+'</p>';
                this.overlay.setPosition(coordinate);
              }
            });
          }
        }
      }
      if(!coordinate){
          this.overlay.setPosition(undefined);
      }
    }
  },

  mounted() {
    this.init();
  }
};
</script>

<style lang="less" scoped>
.map-box,
.map {
  height: 100%;
}
.ol-popup {
  position: absolute;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 280px;
}
.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}
.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}
.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}
.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}
.ol-popup-closer:after {
  content: "✖";
}
</style>
`